package com.yin.ketech.controller.user;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yin.ketech.common.model.Result;
import com.yin.ketech.common.websocket.WebSocketServer;
import com.yin.ketech.entity.user.SysUser;
import com.yin.ketech.service.user.ISysUserService;
import com.yin.ketech.util.RedisTokenUtils;
import com.yin.ketech.vo.user.SysUserVO;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import com.yin.ketech.controller.BaseController;

import javax.validation.Valid;
import java.io.IOException;

/**
 * @ClassName SysUserController
 * @Author luzw
 * @Description
 * @Version V1.0
 * @Date 2020/6/2 16:48
 **/
@RestController
@RequestMapping("/user")
@Api(value = "user", tags = "用户管理模块")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisTokenUtils redisTokenUtils;

    @ApiOperation("登陆")
    @PostMapping("/login")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "username", value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "password", value = "密码", required = true, dataType = "String") })
    public Result<SysUserVO> login(String username, String password){
        SysUser loginUser = sysUserService.selectByUsername(username);
        if(loginUser == null || !loginUser.getPassword().equals(password)){
            return Result.error("用户名或密码错误!");
        }
        SysUserVO sysUserVO = new SysUserVO();
        BeanUtil.copyProperties(loginUser, sysUserVO);
        String token = redisTokenUtils.createToken(username);
        sysUserVO.setAccessToken(token);
        return Result.ok(sysUserVO);
    }

    @PostMapping("/")
    @ApiOperation("新增用户")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    public Result<SysUser> add(@RequestBody @Valid  SysUser sysUser, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return Result.error(bindingResult.getFieldError().getDefaultMessage());
        }
        sysUserService.save(sysUser);
        return Result.ok(sysUser);
    }

    @GetMapping("/{id}")
    @ApiOperation("查询用户")
    @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "String")
    public Result<SysUser> get(@PathVariable("id") String id) throws IOException {
        SysUser sysUser = sysUserService.getById(id);
        WebSocketServer.publishByUniqueId(sysUser.getUsername(), JSONUtil.toJsonStr(sysUser));
        return Result.ok(sysUser);
    }

    @GetMapping("/list")
    @ApiOperation("分页查询所有用户")
    public Result<SysUser> list(Page page, SysUser sysUser){
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        IPage<SysUser> ipage = sysUserService.page(page, queryWrapper);
        return Result.page(ipage);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "String")
    public Result del(@PathVariable("id") String id){
        sysUserService.removeById(id);
        return Result.ok();
    }
}
